package abc.datasource;

import abc.utils.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

public class DynamicDataSource extends AbstractRoutingDataSource {

    IDynamicDataSourceProvider dynamicDataSourceProvider;

    public DynamicDataSource(IDynamicDataSourceProvider dynamicDataSourceProvider) {
        this.dynamicDataSourceProvider = dynamicDataSourceProvider;
        Map<String, DataSource> dsMap = dynamicDataSourceProvider.loadDataSources();
        Map<Object, Object> targetDataSources = new HashMap<>(dsMap);
        super.setTargetDataSources(targetDataSources);
        super.setDefaultTargetDataSource(dsMap.get(IDynamicDataSourceProvider.DEFAULT_DATASOURCE));
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        String dataSourceType = DynamicDataSourceContextHolder.getDataSourceType();
        if(StringUtil.isEmpty(dataSourceType)) {
            if(StringUtil.isEmpty(dynamicDataSourceProvider.getPrimary())) {
                return "master";
            }
            return dynamicDataSourceProvider.getPrimary();
        }
        return dataSourceType;
    }
}
